package com.zmn.oms.zmn.normal.business.impl.part;

import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.redis.lock.DistributedLock;
import com.zmn.manager.redis.lock.DistributedLockUtils;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.common.enums.WorkPartUseTypeEnum;
import com.zmn.oms.business.interfaces.work.OrderWorkAmountBService;
import com.zmn.oms.model.dio.part.OrderPartReviewDIO;
import com.zmn.oms.model.dto.work.modify.PartQueryDTO;
import com.zmn.oms.model.entity.part.OrderPartAddition;
import com.zmn.oms.model.entity.quotation3.OrderQuotationProcess;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.services.interfaces.part.OrderPartAdditionService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationProcessService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.zmn.business.interfaces.quotation3.OrderQuotation3ModifyBService;
import com.zmn.scm2.dubbo.interfaces.scm.engineer.purchase.EngineerPurchaseListRemoteService;
import com.zmn.scm2.dubbo.interfaces.scm.maintenance.order.use.MaintenanceOrderUseListRemoteService;
import jdk.nashorn.internal.objects.Global;
import org.apache.dubbo.config.annotation.Reference;
import com.github.ltsopensource.core.json.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.part.OrderPartBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.MathUtil;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderPartDIO;
import com.zmn.oms.model.dto.part.*;
import com.zmn.oms.model.dto.work.modify.OrderNewMachinePartListDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsPartDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsPartMasterDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsPartMasterDetailDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPost;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.part.OrderPart;
import com.zmn.oms.model.entity.post.OrderPost;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.factorypart.NewPartVO;
import com.zmn.oms.model.vo.part.PartReimburseVO;
import com.zmn.oms.model.vo.work.modify.must.ZsPartMasterDetailVO;
import com.zmn.oms.model.vo.work.modify.must.ZsPartMasterVO;
import com.zmn.oms.model.vo.work.modify.must.ZsPartVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.express.OrderPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.part.OrderPartService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderFactoryPartBService;
import com.zmn.oms.zmn.normal.business.interfaces.part.ZsNormalOrderPartBService;
import com.zmn.scm2.common.model.dro.BasePageDRO;
import com.zmn.scm2.common.model.dro.scm.engineer.warehouse.EngineerWarehouseDRO;
import com.zmn.scm2.common.model.dro.wms.goods.WmsGoodsDRO;
import com.zmn.scm2.common.model.query.wms.goods.WmsGoodsQuery;
import com.zmn.scm2.dubbo.interfaces.scm.engineer.warehouse.EngineerWarehouseListRemoteService;
import com.zmn.scm2.dubbo.interfaces.wms.goods.GoodsListRemoteService;
import com.zmn.tapi.common.expressage.Expressage;
import com.zmn.tapi.dubbo.interfaces.expressage.ExpressageRemoteService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 类描述：啄木鸟-普通工单-配件实现
 *
 * @author heciqi
 * @date 2018/11/28 19:39
 */
@Service
public class ZsNormalOrderPartBServiceImpl implements ZsNormalOrderPartBService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	protected OrderMasterService orderMasterService;
	@Autowired
	protected OrderPartBService orderPartBService;
	@Autowired
	protected OrderPartService orderPartService;
	@Autowired
	protected OrderWorkService orderWorkService;
	@Autowired
	protected OrderPostService orderPostService;
	@Autowired
	protected OrderFactoryPartService orderFactoryPartService;
	@Autowired
	protected ZsOrderFactoryPartBService zsOrderFactoryPartBService;
	@Autowired
	protected OrderFactoryPartPostService orderFactoryPartPostService;
	@Autowired
	OrderDetailService orderDetailService;
	@Autowired
	private ServItemBService servItemBService;
	@Autowired
	private OrderServiceItemService orderServiceItemService;
	@Autowired
	private OrderPartAdditionService orderPartAdditionService;
	@Autowired
	private OrderWorkAmountBService orderWorkAmountBService;
	@Autowired
	private OrderQuotation3ModifyBService orderQuotation3ModifyBService;
	@Autowired
	private OrderQuotationProcessService orderQuotationProcessService;

	@Reference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false, timeout = 8000)
	protected EngineerWarehouseListRemoteService engineerWarehouseListRemoteService;
	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
	private ExpressageRemoteService expressageRemoteService;
	@Reference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private MaintenanceOrderUseListRemoteService maintenanceOrderUseListRemoteService;
	@DubboReference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
	private GoodsListRemoteService goodsListRemoteService;
	@Reference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
	EngineerPurchaseListRemoteService engineerPurchaseListRemoteService;


	@Override
	public ZsPartVO findPartVo(Long orderId, Long workId) throws OmsBaseException {

		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);


		ZsPartVO partVO = new ZsPartVO();
		partVO.setOrderId(orderId);
		partVO.setWorkId(workId);
		partVO.setPartUse(orderWork.getPartUse());

		List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, workId);
		List<OrderPart> partList = orderPartService.listByOrderId(orderId);

		// 已使用的配件map
		Map<Integer, Map<Integer, List<OrderPart>>> usePartMap = partList.stream()
				.collect(Collectors.groupingBy(OrderPart::getMasterId,
						Collectors.groupingBy(OrderPart::getPartType)));

		// 工程师配件
		List<ZsPartMasterVO> partMasterVOList = Lists.newArrayList();
		for (OrderMaster master : masterList) {
			ZsPartMasterVO partMasterVO = new ZsPartMasterVO();
			partMasterVO.setMasterId(master.getMasterId());
			partMasterVO.setMasterName(master.getMasterName());
			partMasterVO.setMasterTypeName(OrderConsts.getOrderMasterTypeName(master.getType()));

			// 组合已使用配件和剩余配件
			List<ZsPartMasterDetailVO> partMasterDetailVOList = processPartMasterDetail(usePartMap, master.getMasterId(), orderWork);
			partMasterVO.setPartMasterDetailVOList(partMasterDetailVOList);
			partMasterVOList.add(partMasterVO);
		}
		partVO.setPartMasterVOList(partMasterVOList);
		return partVO;
	}

	@Override
	public ResponseDTO checkGoodsIndicators(ZsPartDTO zsPartDTO) throws OmsBaseException {

		if (Objects.isNull(zsPartDTO)) {
			throw new OmsBaseException("参数不能为Null");
		}

		// 未使用内采配件
		if (Objects.equals(zsPartDTO.getUsed(), GlobalConsts.NO)) {
			return ResponseDTO.success();
		}

		// 筛选出使用的配件
		Long orderId = zsPartDTO.getOrderId();
		Long workId = zsPartDTO.getWorkId();

		// 组装使用的配件
		List<OrderPart> orderParts = Lists.newArrayList();
		List<ZsPartMasterDTO> partMasterDTOList = zsPartDTO.getPartMasterDTOList();
		partMasterDTOList.forEach(partMasterDTO -> {
			// 过滤出使用过的配件
			List<ZsPartMasterDetailDTO> usePartList = partMasterDTO.getPartMasterDetailDTOList()
					.stream()
					.filter(e -> e.getUseNumber().floatValue() > 0)
					.collect(Collectors.toList());

			usePartList.forEach(partMasterDetailDTO -> {
				OrderPart orderPart = new OrderPart();
				BeanMapper.copy(partMasterDetailDTO, orderPart);
				orderPart.setOrderId(orderId);
				orderPart.setPartType(OrderConsts.PART_TYPE_SOURCING_IN);
				//后台核配件
				if (Objects.isNull(partMasterDetailDTO.getMasterId())){
					orderPart.setMasterId(partMasterDTO.getMasterId());
					orderPart.setMasterName(partMasterDTO.getMasterName());
				}

				orderPart.setNumber(partMasterDetailDTO.getUseNumber());
				orderPart.setReimburse(GlobalConsts.NO);
				orderParts.add(orderPart);
			});
		});

		// 校验配件指标
		CheckOrderPartIndicatorsDTO dto = new CheckOrderPartIndicatorsDTO();
		dto.setOrderId(orderId);
		dto.setWorkId(workId);
		dto.setPartType(OrderConsts.PART_TYPE_SOURCING_IN);
		dto.setOrderPartList(orderParts);
		orderPartBService.checkOrderGoodsIndicators(dto);

		return ResponseDTO.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_PART)
	public ResponseDTO savePart(ZsPartDTO zsPartDTO) throws OmsBaseException {

		OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(zsPartDTO.getOrderId(), zsPartDTO.getWorkId());
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
			throw new OmsBaseException("此工单已收单，不可操作配件");
		}

		// 一口价订单判断是否有优惠删除
		this.canModifyPartByFinalPrice(orderWork);

		String lockKey = String.format(LockConsts.LOCK_ORDER_SAVE_PART, zsPartDTO.getOrderId(), zsPartDTO.getWorkId());
		DistributedLock lock = DistributedLockUtils.build(lockKey, LockConsts.LOCK_VALID_TIME);
		try {
			if (lock.tryLock()) {
				this.modifyPart(orderWork, zsPartDTO);
			}
		} catch (Exception e) {
			logger.error("{}核配件失败：{}", zsPartDTO.getWorkId(), e);
			throw e;
		}finally {
			lock.unlock();
		}

		// 一口价订单处理
		if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
			boolean clearStatus = orderQuotation3ModifyBService.clearEngineerDiscount(orderWork, true);
			if (clearStatus) {
				return ResponseDTO.fail(OrderFailConsts.FAIL_DATA_CHANGE_CLEAR_ENGINEER_DISCOUNT, "配件变更，请重新推送人工优惠");
			}
		}

		return ResponseDTO.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_PART)
	public ResponseDTO cancelPart(ZsPartDTO zsPartDTO) throws OmsBaseException {

		OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(zsPartDTO.getOrderId(), zsPartDTO.getWorkId());
		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)){
			throw new OmsBaseException("此工单已收单，不可操作配件");
		}

		// 一口价订单判断是否有优惠删除
		this.canModifyPartByFinalPrice(orderWork);

		orderPartBService.clearOrderPart(zsPartDTO.getOrderId(), zsPartDTO.getOperatorId(), zsPartDTO.getOperator());

		OrderPartReviewDIO orderPartReviewDIO = new OrderPartReviewDIO();
		orderPartReviewDIO.setReviewStatus(GlobalConsts.NONE);
		orderPartReviewDIO.setWorkId(zsPartDTO.getWorkId());
		orderPartReviewDIO.setOperator(zsPartDTO.getOperator());
		orderPartReviewDIO.setPartUse(GlobalConsts.NO);
		this.modifyOrderPartReview(orderPartReviewDIO);

		// 一口价订单删除优惠
		if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
			boolean clearStatus = orderQuotation3ModifyBService.clearEngineerDiscount(orderWork, true);
			if (clearStatus) {
				return ResponseDTO.fail(OrderFailConsts.FAIL_DATA_CHANGE_CLEAR_ENGINEER_DISCOUNT, "配件变更，请重新推送人工优惠");
			}
		}

		return ResponseDTO.success();
	}

	/**
	 * 处理工程师配件的使用情况
	 *
	 * @param usePartMap 已使用使用配件 key：工程师id
	 */
	private List<ZsPartMasterDetailVO> processPartMasterDetail(
			Map<Integer, Map<Integer, List<OrderPart>>> usePartMap, Integer masterId, OrderWork orderWork)
			throws OmsBaseException {

		List<ZsPartMasterDetailVO> partMasterDetailVOList = Lists.newArrayList();
		PartQueryDTO partQueryDTO = PartQueryDTO
				.builder()
				.masterId(masterId)
				.categId(orderWork.getCategId())
				.servCategId(orderWork.getServCategId())
				.servItemType(orderWork.getServItemType())
				.orderId(orderWork.getOrderId())
				.workId(orderWork.getWorkId())
				.build();
		ResponseDTO<BasePageDRO<EngineerWarehouseDRO>> responseDTO = servItemBService.listPageEngineerWarehouseByQueryV2(partQueryDTO);
		if (!responseDTO.isSuccess()) {
			throw new OmsBaseException("获取工程师配件库存失败");
		}

		Map<Integer, List<OrderPart>> masterPartMap = usePartMap.get(masterId);

		// 工单使用的配件 核配件只取内采配件 key 为领用单Id value key 为配件Id
		Map<String, Map<String, OrderPart>> masterInPartMap = Maps.newHashMap();
		if (masterPartMap != null && masterPartMap.containsKey(OrderConsts.PART_TYPE_SOURCING_IN)) {
			List<OrderPart> inPartList = masterPartMap.get(OrderConsts.PART_TYPE_SOURCING_IN);
			if (!CollectionUtils.isEmpty(inPartList)) {
				masterInPartMap = inPartList.stream().filter(e->e.getPartId()!=null && e.getDrawId()!=null)
						.collect(Collectors.groupingBy(OrderPart::getDrawId,
								Collectors.toMap(OrderPart::getPartId, orderPart -> orderPart)));
			}
		}

		// 组合剩余配件和已使用的配件 将已使用的从masterInPartMap中删除
		List<EngineerWarehouseDRO> items = responseDTO.getData().getItems();
		for (EngineerWarehouseDRO item : items) {
			ZsPartMasterDetailVO partMasterDetailVO = new ZsPartMasterDetailVO();
			BeanUtils.copyProperties(item, partMasterDetailVO);
			partMasterDetailVO.setPartId(item.getGoodsId());
			partMasterDetailVO.setPartName(item.getGoodsName());
			partMasterDetailVO.setDrawId(item.getSaleOrderId());
			partMasterDetailVO.setCategId(item.getCategTwoId());
			partMasterDetailVO.setCategName(item.getCategTwoName());
			partMasterDetailVO.setPayType(item.getPaymentMethod());
			partMasterDetailVO.setImgSrc(item.getImage());

			partMasterDetailVO.setPrice(Optional.ofNullable(item.getPriceFen()).orElse(0));
			partMasterDetailVO.setCostPrice(Optional.ofNullable(item.getCostPriceFen()).orElse(0));
			partMasterDetailVO.setPurchasePrice(Optional.ofNullable(item.getPurchaseCostPriceFen()).orElse(0));

			partMasterDetailVO.setUnit(item.getUnitName());
			partMasterDetailVO.setPartFullName(String.format("%s-%s-%s", partMasterDetailVO.getCategOneName(),
					partMasterDetailVO.getCategName(), partMasterDetailVO.getPartName()));

			// 剩余配件数量
			partMasterDetailVO.setRemainingNumber(item.getCount());
			partMasterDetailVO.setDrawTime(item.getCreateTime());

			// 使用数量
			boolean masterInPartEmpty = masterInPartMap.isEmpty();
			boolean drawIdEmpty = !masterInPartMap.containsKey(item.getSaleOrderId());
			boolean partEmpty = true;
			if (!drawIdEmpty) {
				// 当前领用单下有没有配件
				Map<String, OrderPart> integerListMap = masterInPartMap.get(item.getSaleOrderId());
				if (integerListMap != null && integerListMap.containsKey(item.getGoodsId())) {
					partEmpty = false;
				}
			}

			// 没有配件则是未使用
			if (masterInPartEmpty || drawIdEmpty || partEmpty) {
				partMasterDetailVO.setUseNumber(new BigDecimal(0));
			} else {
				Map<String, OrderPart> drawMap = masterInPartMap
						.get(item.getSaleOrderId());
				OrderPart part = drawMap.get(item.getGoodsId());
				partMasterDetailVO.setUseNumber(part.getNumber());
				partMasterDetailVO.setComparisonImgSrc(part.getComparisonImgSrc());
				drawMap.remove(item.getGoodsId());
			}
			// 计算配件总数
			partMasterDetailVO.setTotalNumber(partMasterDetailVO.getRemainingNumber().add(partMasterDetailVO.getUseNumber()));

			partMasterDetailVOList.add(partMasterDetailVO);
		}

		List<Integer> categIds = masterInPartMap.values()
				.stream()
				.map(Map::values)
				.flatMap(Collection::stream)
				.map(OrderPart::getCategId)
				.collect(Collectors.toList());
		// 如果分类Ids集合为null 说明配件都被使用了
		if (CollectionUtil.isNotNullOrEmpty(categIds)) {

			List<WmsGoodsDRO> wmsGoodsDROList = this.listGoodsByCategIds(categIds);
			// 是否需要上传新旧配件照Map
			Map<String, Integer> hasNeedImgMap = wmsGoodsDROList.stream()
					.collect(Collectors.toMap(WmsGoodsDRO::getGoodsId, WmsGoodsDRO::getNeedImg, (older, newer) -> older));

			// 组装仓库用完的配件 仓库剩余数量为0
			masterInPartMap.forEach((key, value) -> {
				value.forEach((key1, orderPart) -> {
					ZsPartMasterDetailVO partMasterDetailVO = new ZsPartMasterDetailVO();
					BeanUtils.copyProperties(orderPart, partMasterDetailVO);
					partMasterDetailVO.setRemainingNumber(new BigDecimal(0));
					partMasterDetailVO.setUseNumber(orderPart.getNumber());
					partMasterDetailVO.setTotalNumber(orderPart.getNumber());
					partMasterDetailVO.setNeedImg(Optional.ofNullable(hasNeedImgMap.get(orderPart.getPartId())).orElse(GlobalConsts.NO));
					partMasterDetailVOList.add(partMasterDetailVO);
				});
			});
		}
		return partMasterDetailVOList;
	}

	/**
	 * 根据分类id集合查询商品列表
	 *
	 * @param cateIds
	 * @return
	 * @author liudi
	 * @since: 2022/3/23 16:18
	 */
	private List<WmsGoodsDRO> listGoodsByCategIds(List<Integer> cateIds) throws OmsBaseException {
		if (CollectionUtil.isNullOrEmpty(cateIds)) {
			return new ArrayList<>();
		}
		WmsGoodsQuery wmsGoodsQuery = new WmsGoodsQuery();
		wmsGoodsQuery.setCategTwoIdList(cateIds);
		logger.info("根据分类id集合查询商品列表 入参 [{}]", com.alibaba.fastjson.JSON.toJSONString(wmsGoodsQuery));
		ResponseDTO<BasePageDRO<WmsGoodsDRO>> basePageDROResponseDTO = goodsListRemoteService.listPageByQueryV2(wmsGoodsQuery);
		logger.info("根据分类id集合查询商品列表 出参 [{}]", com.alibaba.fastjson.JSON.toJSONString(basePageDROResponseDTO));
		if (!basePageDROResponseDTO.isSuccess()) {
			logger.error("根据分类id集合查询商品列表失败！！ [{}]", basePageDROResponseDTO.getMessage());
			throw new OmsBaseException("根据分类id集合查询商品列表失败！！");
		}
		return basePageDROResponseDTO.getData().getItems();
	}

	/**
	 * 根据工单id查询
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public OrderPartDTO listByOrderId(Long orderId) {
		return orderPartBService.listByOrderId(orderId);
	}

	/**
	 * 根据工单id，工程师id查询
	 *
	 * @param orderId
	 * @param masterId
	 * @return
	 */
	@Override
	public SingleMasterOrderPartDTO listByOrderIdAndMaster(Long orderId, Integer masterId) {
		return orderPartBService.listByOrderIdAndMaster(orderId, masterId);
	}

	/**
	 * 处理配件审核
	 * @param orderPartReviewDIO
	 */
	@Override
	public void modifyOrderPartReview(OrderPartReviewDIO orderPartReviewDIO) {
		try {
			OrderPartAddition dbOrderPartAddition = orderPartAdditionService.findById(orderPartReviewDIO.getWorkId(), orderPartReviewDIO.getWorkId());
			if (Objects.isNull(dbOrderPartAddition)) {
				// 如果数据库没有记录，并且操作未使用配件，直接返回不需要再插入无用数据
				if (Objects.nonNull(orderPartReviewDIO.getPartUse())) {
					return;
				}

				Date now = DateUtil.getNow();
				OrderPartAddition orderPartAddition = new OrderPartAddition();
				orderPartAddition.setWorkId(orderPartReviewDIO.getWorkId());
				orderPartAddition.setOrderId(orderPartReviewDIO.getWorkId());
				if (Objects.equals(orderPartReviewDIO.getReviewStatus(), GlobalConsts.LEVEL_3)) {
					orderPartAddition.setReviewStatus(GlobalConsts.NONE);
				} else {
					orderPartAddition.setReviewStatus(orderPartReviewDIO.getReviewStatus());
				}
				orderPartAddition.setCreater(orderPartReviewDIO.getOperator());
				orderPartAddition.setUpdater(orderPartReviewDIO.getOperator());
				orderPartAddition.setCreateTime(now);
				orderPartAddition.setUpdateTime(now);
				orderPartAdditionService.insert(orderPartAddition);
			} else {
				OrderPartAddition orderPartAddition = new OrderPartAddition();
				orderPartAddition.setWorkId(orderPartReviewDIO.getWorkId());
				orderPartAddition.setOrderId(orderPartReviewDIO.getWorkId());
				if (Objects.equals(orderPartReviewDIO.getReviewStatus(), GlobalConsts.LEVEL_3)) {
					orderPartAddition.setReviewStatus(GlobalConsts.NONE);
				} else {
					orderPartAddition.setReviewStatus(orderPartReviewDIO.getReviewStatus());
				}
				orderPartAddition.setUpdater(orderPartReviewDIO.getOperator());
				orderPartAdditionService.updateByKey(orderPartAddition);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}]更改配件审核异常：【{}】", orderPartReviewDIO.getWorkId(), e.getMessage());
		}
	}

	/**
	 * 新增外报配件
	 *
	 * @param addOrderPartDTO
	 */
	@Override
	public void insertOutOrderPart(AddOrderPartDTO addOrderPartDTO) {
		//orderPartBService.insertOutOrderPart(addOrderPartDTO);

	}

	/**
	 * 新增订单杂项费用
	 *
	 * @param addOrderPartDTO
	 */
	@Override
	public void insertDeliverOrderPart(AddOrderPartDTO addOrderPartDTO) {
		//orderPartBService.insertDeliverOrderPart(addOrderPartDTO);
	}

	/**
	 * 配件报销，包含外报配件和运杂费
	 * @param partReimburseDTO
	 * @return void
	 * @author wangxiaokun
	 */
	@Override
	public void insertReimburseOrderPart(PartReimburseDTO partReimburseDTO){
		AddOrderPartDTO addOrderPartDTO = new AddOrderPartDTO();
		addOrderPartDTO.setOrderId(Long.valueOf(partReimburseDTO.getOrderId()));
		addOrderPartDTO.setWorkId(Long.valueOf(partReimburseDTO.getOrderId()));

		// 操作者信息
		addOrderPartDTO.setOperator(partReimburseDTO.getAuditer());
		addOrderPartDTO.setOperatorId(partReimburseDTO.getAuditerId().longValue());
		addOrderPartDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_STAFF);

		// 外报配件
		if (Objects.equals(partReimburseDTO.getType(), OrderConsts.PART_TYPE_SOURCING_OUT)){

			List<OrderPart> parts = new ArrayList<>(partReimburseDTO.getReimburseItemPartList().size());
			partReimburseDTO.getReimburseItemPartList().forEach(reimburseOutPartDTO -> {
				OrderPart orderPart = new OrderPart();
				orderPart.setPartType(partReimburseDTO.getType());
				orderPart.setPayType(partReimburseDTO.getPayType());
				orderPart.setReimburseId(partReimburseDTO.getReimburseId());
				orderPart.setMasterId(partReimburseDTO.getApplyerId());
				orderPart.setMasterName(partReimburseDTO.getApplyer());

				orderPart.setCategOneId(reimburseOutPartDTO.getCategOneId());
				orderPart.setCategOneName(reimburseOutPartDTO.getCategOneName());
				orderPart.setCategId(reimburseOutPartDTO.getCategTwoId());
				orderPart.setCategName(reimburseOutPartDTO.getCategTwoName());
				orderPart.setPartId(reimburseOutPartDTO.getGoodsId());
				orderPart.setPartName(reimburseOutPartDTO.getGoodsName());
				orderPart.setDrawId(String.valueOf(reimburseOutPartDTO.getItemId()));
				orderPart.setPartFullName(reimburseOutPartDTO.getCategOneName() + "-"
						+ reimburseOutPartDTO.getCategTwoName() + "-" + reimburseOutPartDTO.getGoodsName());

				orderPart.setNumber(reimburseOutPartDTO.getNumber());
				orderPart.setPrice(reimburseOutPartDTO.getPrice());
				orderPart.setDeclarePrice(reimburseOutPartDTO.getAuditAmount());
				orderPart.setUnit(reimburseOutPartDTO.getUnitName());
				orderPart.setRemark(partReimburseDTO.getRemark());

				orderPart.setSettlementSubjectType(Optional.of(partReimburseDTO.getSettlementSubjectType()).orElse(GlobalConsts.NONE));
				// 新旧配件对比照
				orderPart.setComparisonImgSrc(reimburseOutPartDTO.getImgSrc());

				parts.add(orderPart);
			});
			addOrderPartDTO.setParts(parts);
			try{
				orderPartBService.insertOutOrderPart(addOrderPartDTO);
			}catch (OmsBaseException e){
				logger.info("工单号:{}，异常:{}", addOrderPartDTO.getOrderId(), e.getMessage());
			}

		}
		// 运杂
		else if (Objects.equals(partReimburseDTO.getType(), 4)){
			List<OrderPart> parts = new ArrayList<>(1);
			ReimburseDeliverPartDTO deliverPartDTO = partReimburseDTO.getReimburseItemCost();
			OrderPart orderPart = new OrderPart();
			orderPart.setPartType(OrderConsts.PART_TYPE_DELIVER);
			orderPart.setPayType(partReimburseDTO.getPayType());
			orderPart.setReimburseId(partReimburseDTO.getReimburseId());
			orderPart.setMasterId(partReimburseDTO.getApplyerId());
			orderPart.setMasterName(partReimburseDTO.getApplyer());

			orderPart.setCategOneId(0);
			orderPart.setCategOneName("其他");
			orderPart.setCategId(0);
			orderPart.setCategName("其他");
			orderPart.setPartId("0");
			orderPart.setPartName(deliverPartDTO.getDeliverTypeName());
			orderPart.setDrawId(String.valueOf(deliverPartDTO.getItemId()));
			orderPart.setPartFullName("其他-其他-" + deliverPartDTO.getDeliverTypeName());

			orderPart.setNumber(new BigDecimal(1));
			orderPart.setPrice(deliverPartDTO.getApplyAmount());
			orderPart.setDeclarePrice(deliverPartDTO.getAuditAmount());
			orderPart.setUnit("个");
			orderPart.setRemark(partReimburseDTO.getRemark());

			orderPart.setSettlementSubjectType(Optional.of(partReimburseDTO.getSettlementSubjectType()).orElse(GlobalConsts.NONE));

			parts.add(orderPart);
			addOrderPartDTO.setParts(parts);
			try {
				orderPartBService.insertDeliverOrderPart(addOrderPartDTO);
			}catch (OmsBaseException e){
				logger.info("工单号:{}，异常:{}", addOrderPartDTO.getOrderId(), e.getMessage());
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_NEW_MACHINE_PART)
	public void addNewMachinePartList(OrderNewMachinePartListDTO dto) throws OmsBaseException {
		List<OrderPost> orderPostList = dto.getOrderPostList();
		// 删除旧新机物流信息
		orderPostService.deleteOrderPostByOrderId(dto.getOrderId());
		// 添加新机物流信息
		if (CollectionUtil.isNotNullOrEmpty(orderPostList)) {
			orderPostService.insertOrderPostList(dto.getOrderId(), orderPostList);
		}

		// 修改之前的厂商配件信息
		List<Integer> oldFactoryPartIdList = null;
		if (CollectionUtil.isNotNullOrEmpty(dto.getNewPartVOS())){
			oldFactoryPartIdList = dto.getNewPartVOS().stream().map(NewPartVO::getFcOrderPartId).collect(Collectors.toList());
		}

		List<FactoryNewOrderPartDIO> already = null;
		if (CollectionUtil.isNotNullOrEmpty(dto.getPartDIOS())){
			// 已存在的配件物流集合
			already = dto.getPartDIOS().stream().filter(
					part -> Objects.nonNull(part.getFcOrderPartId())).collect(Collectors.toList());
		}

		// 如果有已存在的厂商配件则修改操作
		if (CollectionUtil.isNotNullOrEmpty(already)){
			OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(dto.getOrderId());
			List<OrderFactoryPartPost> factoryPartPosts = Lists.newArrayListWithCapacity(already.size());
			for (FactoryNewOrderPartDIO part : already){
				if (CollectionUtil.isNotNullOrEmpty(oldFactoryPartIdList)
						&& oldFactoryPartIdList.contains(part.getFcOrderPartId())){
					oldFactoryPartIdList.remove(part.getFcOrderPartId());
				}
				OrderFactoryPartPost partPost = BeanMapper.map(part, OrderFactoryPartPost.class);
				partPost.setPostAddressType(part.getPostTarget());
				partPost.setAssignExpressCompany(GlobalConsts.NO);
				if (Objects.equals(OrderFactoryPartConsts.POST_YEYX_ADDRESS, part.getPostTarget())) {
					partPost.setConsigneeName("言而有信公司");
					partPost.setConsigneePhone("4000665315");
					partPost.setAddress("重庆市-渝北区-互联网产业园二期8号楼12层");
				} else {
					partPost.setConsigneeName(orderDetail.getUserName());
					partPost.setConsigneePhone(orderDetail.getTelephone());
					partPost.setAddress(String.format("%s%s%s%s", orderDetail.getProvinceName(), orderDetail.getCityName(), orderDetail.getCountyName(), orderDetail.getAddress()));
				}

				// 订阅物流
				ResponseDTO responseDTO = expressageRemoteService.subscribe(partPost.getExpressCompanyCode(),
						partPost.getExpressCode());
				logger.info("[{}] 订阅结果：{}", partPost, responseDTO.getMessage());

				// 查询快递信息
				logger.info("#orderFactoryPart 查询物流信息 入参：{}, {}", partPost.getExpressCompanyCode(),
						partPost.getExpressCode());
				ResponseDTO<Expressage> responseExpressage = expressageRemoteService.getExpressageByCompanyAndCode(
						partPost.getExpressCompanyCode(), partPost.getExpressCode());
				logger.info("#orderFactoryPart 查询物流信息 出参：{}", JSON.toJSONString(responseExpressage));
				if (Objects.nonNull(responseExpressage.getData())) {
					Expressage expressageDRO = responseExpressage.getData();
					partPost.setStatus(OrderPostConsts.getZmnPostStatus(expressageDRO.getState()));
					if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(expressageDRO.getList())) {
						partPost.setExpressData(com.alibaba.fastjson.JSON.toJSONString(expressageDRO.getList()));
					}
				}

				factoryPartPosts.add(partPost);
			}
			// 修改厂商配件物流
			orderFactoryPartPostService.updateExpressById(factoryPartPosts);
		}

		// 删除：页面点击删除的厂商配件和物流
		if (CollectionUtil.isNotNullOrEmpty(oldFactoryPartIdList)){
			oldFactoryPartIdList.forEach(id -> {
				orderFactoryPartService.deleteByKey(id);
				orderFactoryPartPostService.deleteByFcOrderPartId(id);
			});
		}

		//如果页面传递List不为空，则插入厂商配件和物流，否则删除配件和物流
		if (CollectionUtil.isNotNullOrEmpty(dto.getPartDIOS())){
			//新添加的配件物流集合
			List<FactoryNewOrderPartDIO> newPart = dto.getPartDIOS().stream().filter(
					part -> Objects.isNull(part.getFcOrderPartId())).collect(Collectors.toList());

			if (CollectionUtil.isNotNullOrEmpty(newPart)){
				newPart.forEach(dio -> {
					dio.setOrderId(dto.getOrderId());
					dio.setOperator(dto.getOperator());
				});
				zsOrderFactoryPartBService.insertPartListAndPost(newPart);
			}
		} else {
			//删除订单的厂商配件
			orderFactoryPartService.deleteByOrderId(dto.getOrderId());
			//删除新件物流信息
			orderFactoryPartPostService.deleteByOrderId(dto.getOrderId());
		}
	}

	/**
	 * 清空工单配件（工单配件，退回工程师库房，更新工单金额）
	 *
	 * @param orderId
	 */
	@Override
	public void clearOrderPart(Long orderId) {
		//orderPartBService.clearOrderPart(orderId);
	}

	/**
	 * 取消配件报销（外报、运杂）
	 * @param orderId
	 * @param reimburseId
	 * @return void
	 * @author wangxiaokun
	 */
	@Override
	public void clearOrderPartByOrderIdAndReimburseId(Long orderId, String reimburseId){
		orderPartBService.clearOrderPartByOrderIdAndReimburseId(orderId, reimburseId);
	}

	/**
	 * @param orderId
	 * @return
	 */
	@Override
	public List<PartReimburseVO> listPartReimburseByOrderId(Long orderId) {
		List<OrderPart> list = orderPartBService.listPartReimburseByOrderId(orderId);
		List<PartReimburseVO> voList = Lists.newArrayList();
		list.forEach(orderPart -> {
			PartReimburseVO vo = new PartReimburseVO();
			vo.setOrderPartId(orderPart.getOrderPartId());
			vo.setApplyId(orderPart.getReimburseId());
			vo.setPartId(orderPart.getPartId());
			vo.setMasterName(orderPart.getMasterName());
			vo.setPartFullName(orderPart.getPartFullName());
			vo.setNumber(orderPart.getNumber());
			vo.setDeclare(MathUtil.amountMultiplyNumber(orderPart.getPrice(), orderPart.getNumber()));
			vo.setPrice(orderPart.getPrice());
			vo.setTotalAmount(MathUtil.amountMultiplyNumber(orderPart.getPrice(), orderPart.getNumber()));
			vo.setType(orderPart.getPartType());
			vo.setTypeName(OrderConsts.getPartTypeName(orderPart.getPartType()));
			vo.setComparisonImgSrc(orderPart.getComparisonImgSrc());
			vo.setAiStatus(orderPart.getAiStatus());
			vo.setAiStatusName(OrderPartConsts.getDeteName(orderPart.getAiStatus()));
			voList.add(vo);
		});
		return voList;
	}

	@Override
	public void updatePartDetectionResult(PartDetectionResultDTO resultDTO) {
		List<OrderPart> list = orderPartService.listByOrderId(resultDTO.getWorkId());
		if (CollectionUtil.isNullOrEmpty(list)) {
			logger.info("工单配件新旧对比照片结果审核失败：{}", JSON.toJSONString(resultDTO));
			return;
		}
		Optional<OrderPart> optional = list.stream().filter(part -> {
			boolean result = Objects.equals(part.getPartType(), resultDTO.getSourceType())
					&& Objects.equals(part.getMasterId(), resultDTO.getMasterId())
					&& Objects.equals(part.getPartId(), resultDTO.getGoodsId());
			if (StringUtil.isNotBlank(resultDTO.getReimburseId())) {
				result = result && Objects.equals(resultDTO.getReimburseId(), part.getReimburseId());
			}
			return result;
		}).findFirst();

		if (optional.isPresent()) {
			OrderPart updatePart = new OrderPart();
			updatePart.setOrderPartId(optional.get().getOrderPartId());
			updatePart.setAiStatus(resultDTO.getAiStatus());
			orderPartService.updateAiStatusByOrderPartId(updatePart);
		}

	}

	/**
	 * 配件使用情况
	 * @param orderWork
	 * @return
	 * @see WorkPartUseTypeEnum
	 */
	@Override
	public Integer getPartUseType(OrderWork orderWork) throws OmsBaseException{
		if (Objects.isNull(orderWork)) {
			return WorkPartUseTypeEnum.NOT_USE.getType();
		}

		if (NumberUtil.isNullOrZero(orderWork.getPartUse())) {
			return WorkPartUseTypeEnum.NOT_USE.getType();
		}

		if (Objects.equals(orderWork.getPartUse(), GlobalConsts.NO)) {
			return WorkPartUseTypeEnum.NOT_USE.getType();
		}

		if (NumberUtil.isNullOrZero(orderWork.getMasterId())) {
			return WorkPartUseTypeEnum.NOT_USE.getType();
		}

		SingleMasterOrderPartDTO singleMasterOrderPartDTO = orderPartBService.listByOrderIdAndMaster(orderWork.getOrderId(), orderWork.getMasterId());
		if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(singleMasterOrderPartDTO.getInParts())) {
			List<Integer> categIds = singleMasterOrderPartDTO.getInParts()
					.stream()
					.filter(e -> StringUtil.isBlank(e.getComparisonImgSrc()))
					.map(OrderPart::getCategId)
					.distinct()
					.collect(Collectors.toList());
			List<WmsGoodsDRO> wmsGoodsDROS = this.listGoodsByCategIds(categIds);
			Map<String, WmsGoodsDRO> goodsDROMap = Maps.uniqueIndex(wmsGoodsDROS, WmsGoodsDRO::getGoodsId);
			for (OrderPart inPart : singleMasterOrderPartDTO.getInParts()) {
				if (StringUtil.isNotBlank(inPart.getComparisonImgSrc())) {
					continue;
				}
				WmsGoodsDRO wmsGoodsDRO = goodsDROMap.get(inPart.getPartId());
				if (Objects.isNull(wmsGoodsDRO)) {
					continue;
				}
				if (Objects.equals(wmsGoodsDRO.getNeedImg(), GlobalConsts.YES)) {
					return WorkPartUseTypeEnum.COMPARISON_IMG_NOT_UPLOADED.getType();
				}
			}
		}

		logger.info("是否有外报未补全对比照#checkExistPending workId={}", orderWork.getWorkId());
		ResponseDTO<Boolean> responseDTO = engineerPurchaseListRemoteService.checkExistPending(String.valueOf(orderWork.getWorkId()));
		logger.info("是否有外报未补全对比照#checkExistPending responseDTO={}", responseDTO);
		if (Objects.equals(responseDTO.getData(), Boolean.TRUE)) {
			return WorkPartUseTypeEnum.COMPARISON_IMG_NOT_UPLOADED.getType();
		}


		return WorkPartUseTypeEnum.COMPARISON_IMG_UPLOADED.getType();
	}

	/**
	 * @param orderParts 原配件数据
	 * @param orderParts   待提交内采配件
	 * @param orderWork    订单信息
	 * @param operatorType 操作人类型
	 * @throws OmsBaseException
	 */
	private void verifyOrderPart(List<OrderPart> orderParts, OrderWork orderWork, Integer operatorType) throws OmsBaseException {
		if (CollectionUtil.isNullOrEmpty(orderParts)) {
			return;
		}

		// 校验内采配件金额不能大于内部价
		if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
			return;
		}

		List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderWork.getOrderId());
		if (!CollectionUtil.isNotNullOrEmpty(orderServiceItemList)) {
			return;
		}

		int internalSettlementPrice = orderServiceItemList.stream()
				.filter(e -> e.getInternalTotalPrice() != null)
				.mapToInt(OrderServiceItem::getInternalTotalPrice).sum();
		int partAmount = orderParts.stream().mapToInt((e) -> MathUtil.amountMultiplyNumber(e.getPrice(), e.getNumber())).sum();
		if (partAmount > internalSettlementPrice) {
			throw new OmsBaseException("内采配件金额大于订单内部价，不允许确定");
		}
//
//		// 工程师操作就不校验了（已经调用过接口校验了）
//		if (Objects.equals(operatorType, GlobalConsts.OPERATE_USER_TYPE_MASTER)) {
//			return;
//		}
//
//		// 校验配件指标
//		CheckOrderPartIndicatorsDTO dto = new CheckOrderPartIndicatorsDTO();
//		dto.setOrderId(orderWork.getOrderId());
//		dto.setWorkId(orderWork.getWorkId());
//		dto.setPartType(OrderConsts.PART_TYPE_SOURCING_IN);
//		dto.setOrderPartList(orderParts);
//		orderPartBService.checkOrderGoodsIndicators(dto);
	}

	/**
	 * 一口价订单判断是否能修改配件
	 * @param orderWork
	 * @return
	 */
	private void canModifyPartByFinalPrice(OrderWork orderWork) throws OmsBaseException{

		if (Objects.isNull(orderWork)) {
			return;
		}

		if (!Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
			return;
		}

		// 判断是否领取工程师优惠
		OrderQuotationProcess dbProcess = orderQuotationProcessService.findByOrderIdSrcMaster(orderWork.getOrderId());
		if (Objects.isNull(dbProcess)) {
			return;
		}

		if (NumberUtil.isNullOrZero(dbProcess.getEngineerDiscountId()) ||
				!Objects.equals(dbProcess.getEngineerDiscountStatus(), GlobalConsts.YES)) {
			return;
		}

		if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING) ||
				orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_COMPLETE) {
			throw new OmsBaseException("一口价工单且使用人工优惠，在工单已完成或取消后，不能进行修改配件操作");
		}
	}

	/**
	 * 修改配件数据
	 * @param orderWork
	 * @param zsPartDTO
	 * @throws OmsBaseException
	 */
	private void modifyPart(OrderWork orderWork, ZsPartDTO zsPartDTO) throws OmsBaseException {

		if (Objects.isNull(orderWork) || Objects.isNull(zsPartDTO)) {
			throw new OmsBaseException("参数不能为Null");
		}

		// 未使用内采配件
		if (Objects.equals(zsPartDTO.getUsed(), GlobalConsts.NO)) {

			// 清除工单配件
			orderPartBService.clearOrderPart(zsPartDTO.getOrderId(), zsPartDTO.getOperatorId(), zsPartDTO.getOperator());

			// 处理配件审核
			OrderPartReviewDIO orderPartReviewDIO = new OrderPartReviewDIO();
			orderPartReviewDIO.setReviewStatus(GlobalConsts.NONE);
			orderPartReviewDIO.setWorkId(zsPartDTO.getWorkId());
			orderPartReviewDIO.setOperator(zsPartDTO.getOperator());
			orderPartReviewDIO.setPartUse(GlobalConsts.NO);
			this.modifyOrderPartReview(orderPartReviewDIO);

			return;
		}

		// 原工单内采配件数据
		OrderPartDTO orderPartDTO = orderPartBService.listByOrderId(zsPartDTO.getOrderId());

		// 筛选出使用的配件
		Long orderId = zsPartDTO.getOrderId();
		Long workId = zsPartDTO.getWorkId();

		// 组装使用的配件
		List<OrderPart> orderParts = Lists.newArrayList();
		List<ZsPartMasterDTO> partMasterDTOList = zsPartDTO.getPartMasterDTOList();
		partMasterDTOList.forEach(partMasterDTO -> {
			// 过滤出使用过的配件
			List<ZsPartMasterDetailDTO> usePartList = partMasterDTO.getPartMasterDetailDTOList()
					.stream()
					.filter(e -> e.getUseNumber().floatValue() > 0)
					.collect(Collectors.toList());

			usePartList.forEach(partMasterDetailDTO -> {
				OrderPart orderPart = new OrderPart();
				BeanMapper.copy(partMasterDetailDTO, orderPart);
				orderPart.setOrderId(orderId);
				orderPart.setPartType(OrderConsts.PART_TYPE_SOURCING_IN);
				//后台核配件
				if (Objects.isNull(partMasterDetailDTO.getMasterId())){
					orderPart.setMasterId(partMasterDTO.getMasterId());
					orderPart.setMasterName(partMasterDTO.getMasterName());
				}

				orderPart.setNumber(partMasterDetailDTO.getUseNumber());
				orderPart.setReimburse(GlobalConsts.NO);
				orderParts.add(orderPart);
			});
		});

		// 校验配件指标
		this.verifyOrderPart(orderParts, orderWork, zsPartDTO.getOperatorType());

		// 保存核配件数据
		OmsBaseException saveException;
		try {
			AddOrderPartDTO addOrderPartDTO = new AddOrderPartDTO();
			addOrderPartDTO.setOrderId(orderId);
			addOrderPartDTO.setWorkId(workId);
			addOrderPartDTO.setParts(orderParts);
			addOrderPartDTO.setOperator(zsPartDTO.getOperator());
			addOrderPartDTO.setOperatorId(zsPartDTO.getOperatorId());
			orderPartBService.insertInOrderPart(addOrderPartDTO);
			return;
		} catch (OmsBaseException e) {
			saveException = e;
		}

		// 异常处理
		if (Objects.isNull(saveException)) {
			throw new OmsBaseException("系统异常");
		}

		if (!Objects.equals(saveException.getCode(), OmsErrorCodeConsts.ERROR_USE_IN_PART_CODE)) {
			throw saveException;
		}

		if (CollectionUtil.isNullOrEmpty(orderPartDTO.getInParts())) {
			throw new OmsBaseException("系统异常请重新核销");
		}

		// 删除工单配件
		orderPartService.deleteByOrderIdAndPartType(orderId, OrderConsts.PART_TYPE_SOURCING_IN);

		// 计算配件金额
		List<OrderPart> list = orderPartService.listByOrderId(orderWork.getOrderId());
		int inSourcingAmount = list.stream().filter(part -> Objects.equals(part.getPartType(), OrderConsts.PART_TYPE_SOURCING_IN)).mapToInt((part) -> MathUtil.amountMultiplyNumber(part.getPrice(), part.getNumber())).sum();
		int outSourcingAmount = list.stream().filter(part -> Objects.equals(part.getPartType(), OrderConsts.PART_TYPE_SOURCING_OUT)).mapToInt((part) -> MathUtil.amountMultiplyNumber(part.getPrice(), part.getNumber())).sum();
		int deliverAmount = list.stream().filter(part -> Objects.equals(part.getPartType(), OrderConsts.PART_TYPE_DELIVER)).mapToInt((part) -> MathUtil.amountMultiplyNumber(part.getPrice(), part.getNumber())).sum();
		int fcPartAmount = Optional.ofNullable(orderWork.getFactoryPartAmount()).orElse(0);
		int partAmount = inSourcingAmount + outSourcingAmount + deliverAmount + fcPartAmount;

		// 更改配件金额
		OrderWork updateWork = new OrderWork();
		updateWork.setOrderId(orderWork.getOrderId());
		updateWork.setWorkId(orderWork.getWorkId());
		updateWork.setPartAmount(partAmount);
		updateWork.setInSourcingAmount(inSourcingAmount);
		updateWork.setOutSourcingAmount(outSourcingAmount);
		updateWork.setDeliverAmount(deliverAmount);
		updateWork.setFactoryPartAmount(fcPartAmount);
		updateWork.setPartUse(partAmount == 0 ? GlobalConsts.NO : GlobalConsts.YES);
		orderWorkAmountBService.updatePartAmount(orderWork);

		throw new OmsBaseException("系统异常请重新核销");
	}
}
